import { _decorator, Component, instantiate, Label, Node, Prefab, find, Button } from 'cc';
const { ccclass, property } = _decorator;

import { LEVEL_DATA } from "./LevelData";
import { LevelItem } from "./LevelItem";
import { GameManager } from './GameManager';

@ccclass('SelectLevelPanelController')
export class SelectLevelPanelController extends Component {
    @property(Prefab)
    levelItemPrefab: Prefab = null;
    
    @property(Node)
    content: Node = null;

    @property(Button)
    backButton: Button = null;

    @property(Button)
    confirmButton: Button = null;

    private selectedLevel: number = -1;
    private levelItems: LevelItem[] = [];
    
    onLoad() {
        // 添加按钮监听，增加空值检查
        if (this.backButton) {
            this.backButton.node.on(Node.EventType.TOUCH_END, this.onBackClicked, this);
        }
        if (this.confirmButton) {
            this.confirmButton.node.on(Node.EventType.TOUCH_END, this.onConfirmClicked, this);
        }
    }
    
    start() {
        this.generateLevelItems();
    }
    
    private generateLevelItems() {
        LEVEL_DATA.forEach((item,index) => {
            const levelItem = instantiate(this.levelItemPrefab);
            const levelItemComp = levelItem.getComponent(LevelItem);
            levelItemComp.setLabel(index + 1);
            levelItemComp.setSelected(false);
            this.levelItems.push(levelItemComp);
            this.content.addChild(levelItem);
        });
    }
    
    onLevelSelected(level: number) {
        console.log(`选择关卡: ${level}`);
        // 更新选中状态
        this.selectedLevel = level;
        // 更新所有关卡项的显示状态
        this.levelItems.forEach(item => {
            item.setSelected(item.getLevel() === level);
        });
    }

    private onBackClicked() {
        GameManager.instance.hideLevelSelection();
    }

    private onConfirmClicked() {
        if (this.selectedLevel === -1) {
            console.log('请先选择关卡');
            return;
        }
        
        GameManager.instance.currentLevel = this.selectedLevel - 1;
        GameManager.instance.hideHomePanel();
        GameManager.instance.restartLevel();
        GameManager.instance.hideLevelSelection();
    }

    onDestroy() {
        // 清理事件监听，增加空值检查
        if (this.backButton && this.backButton.node) {
            this.backButton.node.off(Node.EventType.TOUCH_END, this.onBackClicked, this);
        }
        if (this.confirmButton && this.confirmButton.node) {
            this.confirmButton.node.off(Node.EventType.TOUCH_END, this.onConfirmClicked, this);
        }
    }
}


